package org.example.im.common.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.example.im.bean.protocol.Packet;
import org.springframework.stereotype.Component;

/**
 * @author dingrui
 * @since 2022/2/11
 * @description 协议头 消息体长度
 * @see org.example.im.bean.protocol.Packet
 */
@Component
public class Spliter extends LengthFieldBasedFrameDecoder {

    public Spliter() {
        super(Integer.MAX_VALUE, Packet.LENGTH_FIELD_OFFSET, Packet.LENGTH_FIELD_LEN);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        // check magic number
        if (PacketCodec.MAGIC_NUMBER != in.getInt(in.readerIndex())) {
            ctx.channel().close();
            return null;
        }
        return super.decode(ctx, in);
    }
}
